package com.jf.blog.controller;

import com.jf.blog.util.ResultJson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@Api(tags = "文件处理模块")
public class FIleController {
    @Value("${filepath}")
    private String filepath;

    @PostMapping("/upload")
    @ApiOperation("上传文件")
    public ResultJson upload(MultipartFile file, String type) {
        if (file == null) {
            return ResultJson.error("上传文件为空");
        }
        if (StringUtils.isEmpty(type) || "null".equals(type)) {
            type = "";
        }
        /*获取文件原名称*/
        String originalFilename = file.getOriginalFilename();
        /*获取文件格式后缀*/
        /*断言*/
        assert originalFilename != null;
        String[] ofs = originalFilename.split("\\.");
        String ext = ofs[ofs.length - 1];
        /*生成新文件名*/
        String filename = UUID.randomUUID() + "." + ext;
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int date = calendar.get(Calendar.DATE);

        String datePath = year + "/" + (month < 10 ? "0" + month : month) + "/" + (date < 10 ? "0" + date : date) + "/";
        /*文件路径*/
        String path = "upload/" + datePath + type + "/";
        /*验证文件夹是否需要创建*/
        File uploadFile = new File(filepath + path);
        if (!uploadFile.exists()) {
            uploadFile.mkdirs();
        }
        /*存储图片*/
        try {
            file.transferTo(new File(uploadFile, filename));
        } catch (IOException e) {
            return ResultJson.error(e.getMessage());
        }
        /*封装json*/
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("filename", "/images/upload/" + datePath + type + "/" + filename);
        return ResultJson.success(map);
    }
}
